package info.androidhive.sqlite;
 
import info.androidhive.sqlite.helper.DatabaseHelper;
import info.androidhive.sqlite.model.Todo;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
 
public class MainActivity extends Activity{
 
    // Database Helper
    DatabaseHelper db;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        db = new DatabaseHelper(getApplicationContext());
        final ArrayList<Todo> arrayList = new ArrayList<Todo>();
        
        //db.deleteToDoAll();
        
        List<Todo> allToDos = db.getAllToDos();
        for (Todo todo : allToDos) {
            arrayList.add(todo);
        }
 
        Button insertButton = (Button)this.findViewById(R.id.insertButton);
      
        ListView listView = (ListView)this.findViewById(R.id.listView);
        final EditText insertTodo = (EditText)this.findViewById(R.id.editTodo);
        
        //final ArrayAdapter<Todo> arrayAdapter = new ArrayAdapter<Todo>(this, android.R.layout.simple_list_item_1, arrayList);
        //listView.setAdapter(arrayAdapter);
        
        final TodoListAdapter arrayAdapter = new TodoListAdapter(this, R.layout.row, arrayList);
        listView.setAdapter(arrayAdapter);
        insertButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String todo;
				todo = insertTodo.getText().toString();
				if(todo == "") return;
				
				Todo new_todo = new Todo(todo);
				long id = db.createToDo(new_todo);
				new_todo.setId((int) id);
				
				arrayList.add(new_todo);
				
				arrayAdapter.notifyDataSetChanged();
				insertTodo.setText("");
			}
		});
        
    	listView.setOnItemLongClickListener(new OnItemLongClickListener() {
    		@Override
    		public boolean onItemLongClick(AdapterView<?> adview, View v, int index, long arg){
    			db.deleteToDo(arrayList.get(index).getId());
    			arrayList.remove(index);
    			arrayAdapter.notifyDataSetChanged();
    			return true;
    		}
    	});
    		
        db.closeDB();
         
    }

    
    
}